package fidel.spring.shiro.demo.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 自定义异常处理器
 * 
 * @version 1.0
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {

    /**
     * 前端控制器DispatcherServlet在进行HandlerMapping、调用HandlerAdapter执行Handler过程中，如果遇到异常就会执行此方法
     * 
     * @param handler 最终要执行的Handler，它的真实身份是HandlerMethod
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {
        // 如果异常属于以下类型
        if (ex instanceof CustomException || ex instanceof UnknownAccountException
            || ex instanceof IncorrectCredentialsException) {
            // 获取异常信息，将异常信息在错误页面展示
            request.setAttribute("message", ex.getMessage());
        } else {
            // 打印异常的堆栈跟踪
            ex.printStackTrace();
            // 将预料之外的异常视为未知错误
            request.setAttribute("message", "未知错误");
        }
        try {
            // 转向到错误页面
            request.getRequestDispatcher("/WEB-INF/page/error.jsp").forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView();
    }

}
